package com.cssw.fyzb.tps.third.tf56pay.sign;

import com.cssw.fyzb.tps.third.tf56pay.common.CharsetEnum;
import com.cssw.fyzb.tps.third.tf56pay.common.JsonResult;
import com.cssw.fyzb.tps.third.tf56pay.common.SignAlgorithmEnum;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * @author roy.caix
 * 2019-04-29 13:38
 **/
public class StandardRSA {

    /**
     * RSA签名
     *
     * @param plaintext 待签名数据
     * @param privateKey 商户私钥
     * @param signAlgorithmEnum 加密算法
     * @return 签名值
     */
    public static JsonResult sign(String plaintext, String privateKey, SignAlgorithmEnum signAlgorithmEnum, CharsetEnum charset) {
        JsonResult jr;
        String sign;
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyFactory.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature.getInstance(signAlgorithmEnum.getAlgorithmName());
            signature.initSign(priKey);
            signature.update(plaintext.getBytes(charset.getCharset()));
            byte[] signed = signature.sign();
            sign = Base64.encodeBase64String(signed);
            jr = new JsonResult("加签成功", 0, "StandardRSA", plaintext, sign);
        } catch (Exception e) {
            jr = new JsonResult("系统加签异常", -1, "StandardRSA", "", "");
        }
        return jr;
    }

}